﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZR.DataCollection.OperationCore.OperationHelper
{
    public class TaskQueue
    {
        private readonly ConcurrentQueue<Func<Task>> _queue = new();
        private readonly SemaphoreSlim _semaphore = new(0);
        private bool _isProcessing;

        public void Enqueue(Func<Task> task)
        {
            _queue.Enqueue(task);
            _semaphore.Release();
        }

        public async Task ProcessQueueAsync()
        {
            if (_isProcessing) return;

            _isProcessing = true;

            while (_queue.TryDequeue(out var task))
            {
                await task();
                _semaphore.Wait();
            }

            _isProcessing = false;
        }
    }
}